<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class ProductController extends Controller
{
    /**
     * 获取商品列表
     *
     * @return JsonResponse
     */
    public function index(): JsonResponse
    {
        Log::info('开始获取商品列表');
        
        try {
            $products = Product::select('id', 'name', 'price')
                ->where('is_saleable', true)
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($product) {
                    $data = $product->toArray();
                    $data['image'] = $product->getFirstMediaUrl('product-images');
                    return $data;
                });
                
            Log::info('获取商品列表成功', [
                'count' => $products->count(),
                'products' => $products->toArray()
            ]);

            return response()->json([
                'code' => 0,
                'message' => 'success',
                'data' => $products
            ]);
        } catch (\Exception $e) {
            Log::error('获取商品列表失败', [
                'error' => $e->getMessage()
            ]);
            
            return response()->json([
                'code' => 1,
                'message' => '获取商品列表失败',
                'data' => []
            ]);
        }
    }
} 